<template>
  <view class="open_team">
    <z-nav-bar id="nav" bgColor="#ffffff" title="开通团体卡"></z-nav-bar>
    <public-loading></public-loading>
    <up-form
      labelPosition="top"
      :model="form"
      :rules="rules"
      labelWidth="150"
      ref="uFormRef"
    >
      <up-form-item
        label="店铺名称"
        prop="shopName"
        :borderBottom="false"
        :required="true"
        v-if="!storeId"
      >
        <view class="search-area">
          <up-search placeholder="搜索门店名称并添加" v-model="searchName" :showAction="false"></up-search>
          <view class="search-shop-pot" :class="{ active: searchOpen}">
            <scroll-view class="search-item-pot" scroll-y="true" >
              <view class="shop-item" v-for="(item,index) in shopList" :key="index">
                <view class="flex-center-between">
                  <view class="title">
                    {{item.storeFullName}}
                  </view>
                  <view class="add flex-a-center">
                    <!-- <image class="small-img" src="http://www.xvopen.com/xiaoV/img1/add.png" mode=""></image>
                  {{item.distance}}km -->
                  </view>
                </view>
                <view class="flex-center-between">
                  <view class="cont">
                    店铺联系方式:{{item.customerService}}
                  </view>
                  <view class="btn"  @click="handleConfirmItem(item)">
                    选择
                  </view>
                </view>
              </view>
            </scroll-view>
          </view>
        </view>
      </up-form-item>
      <up-form-item
        label="申请企业名称"
        prop="companyName"
        :borderBottom="false"
        :required="true"
        v-if="form.groupCardType ==='A'"
      >
        <view class="round_wrap">
          <up-input
            v-model="form.companyName"
            placeholder="请输入企业名称"
            :border="false"
            :required="true"
            fontSize="28rpx"
            :placeholderStyle="placeholderStyle"
          ></up-input>
        </view>
      </up-form-item>
      <up-form-item
        label="申请额度"
        prop="appliedAmount"
        :borderBottom="false"
        :required="true"
      >
        <view class="round_wrap">
          <up-input
            type="number"
            v-model="form.appliedAmount"
            placeholder="请输入申请额度"
            :border="false"
            :required="true"
            fontSize="28rpx"
            :placeholderStyle="placeholderStyle"
          ></up-input>
        </view>
        <view class="tips" v-if="storeId">* 最高额度：{{form.groupCardType==='A' ? shopInfo.businessAuthorizedAmount: shopInfo.familyAuthorizedAmount}}元</view>
          <view class="tips" v-else>* 最高额度：{{form.groupCardType==='A' ? ohterStore.businessAuthorizedAmount: ohterStore.familyAuthorizedAmount}}元</view>
      </up-form-item>
      <up-form-item
        label="申请人名称"
        prop="applicantName"
        :borderBottom="false"
        :required="true"
      >
        <view class="round_wrap">
          <up-input
            v-model="form.applicantName"
            placeholder="请输入申请人名称"
            :border="false"
            :required="true"
            fontSize="28rpx"
            :placeholderStyle="placeholderStyle"
          ></up-input>
        </view>
      </up-form-item>
      <up-form-item
        label="绑定手机号"
        prop="phoneNumber"
        :borderBottom="false"
        :required="true"
      >
        <view class="round_wrap">
          <up-input
            type="number"
            v-model="form.phoneNumber"
            placeholder="请输入绑定手机号"
            :border="false"
            :required="true"
            fontSize="28rpx"
            :placeholderStyle="placeholderStyle"
          ></up-input>
        </view>
      </up-form-item>
      <up-form-item
        label="获取验证码"
        prop="verificationCode"
        :borderBottom="false"
        :required="true"
      >
        <view class="round_wrap df flex-aj-center">
          <up-input
            v-model="form.verificationCode"
            placeholder="请输入获取验证码"
            :border="false"
            :required="true"
            fontSize="28rpx"
            :placeholderStyle="placeholderStyle"
          ></up-input>
          <view
            :class="{ disabled: isCounting }"
            @tap="getCode"
          >
            {{ isCounting ? countdown + '秒后重试' : '获取验证码' }}
          </view>
        </view>
      </up-form-item>
      <up-form-item
        label="身份证上传"

        :borderBottom="false"
        :required="true"
      >
        <view class="uploader previous">
          <z-upload-image limit="1" v-model:files="form.idCardFront" action-type="custom">
            <view class="adrift">
              <image class="icon" src="http://www.xvopen.com/xiaoV/img1/camera.png"></image>
              <view class="describe">请上传清晰的身份证人像面照片</view>
            </view>
          </z-upload-image>
        </view>
        <view class="uploader">
          <z-upload-image limit="1" v-model:files="form.idCardBack" action-type="custom">
            <view class="adrift">
              <image class="icon" src="http://www.xvopen.com/xiaoV/img1/camera.png"></image>
              <view class="describe">请上传清晰的身份证国徽面照片</view>
            </view>
          </z-upload-image>
        </view>
      </up-form-item>
      <up-form-item
        label="营业执照"

        :borderBottom="false"
        :required="true"
        v-if="form.groupCardType ==='A'"
      >
        <view class="uploader previous">
          <z-upload-image limit="1" v-model:files="form.businessLicense" action-type="custom">
            <view class="adrift">
              <image class="icon" src="http://www.xvopen.com/xiaoV/img1/camera.png"></image>
              <view class="describe">请上传营业执照</view>
            </view>
          </z-upload-image>
        </view>
      </up-form-item>
    </up-form>
    <view class="bottom-btn-box" >
      <main-button :color="'#fff'" :margin="'24rpx 0 0'" @click="submit">申请</main-button>
    </view>
  </view>
</template>

<script setup>
import { ref, reactive ,watch} from 'vue';
import { onLoad } from '@dcloudio/uni-app';
import {useCustomStores} from '@/utils/hook'
import {groupAdd} from '@/api/pagesMy/user'
import { qryIndexList} from '@/api/home'
import {

  storeDetailsId,
} from '@/api/pagesShop'
import {smsCode} from '../../api/pagesMy/user'
const {ShopStore} = useCustomStores()
const {shopInfo} = ShopStore
// 使用 ref 创建响应式引用
const form = ref({
  storeId:"",
  groupCardType:"", //A 企业团体卡 B 家庭团体卡
  companyName:"",//申请企业名称
  appliedAmount:"",//申请额度
  applicantName:"",//申请人名称
  phoneNumber:"",//绑定手机号
  idCardFront:"",
  idCardBack:"",
  businessLicense:"",
  verificationCode:"",


});
const storeId =ref('');
const ohterStore = ref({
  businessAuthorizedAmount: 0,
  familyAuthorizedAmount: 0,
});
const tips = ref('');
const seconds = ref(10);
const uCodeRef = ref(null);
const codeChange = (text) => {
  tips.value = text;
};
const placeholderStyle =ref({
  fontSize:'24rpx',
  color:'red'
})
const searchName = ref('');
const searchOpen = ref(false);
const searchFlag = ref(false)
const shopList = ref([])
const rules= ref({
  shopName: [
    { required: true, message: '请输入店铺名称', trigger: 'blur' },
  ],
  companyName: [
    { required: true, message: '请输入企业名称', trigger: 'blur' },
  ],
  appliedAmount: [
    { required: true, message: '请输入申请额度', trigger: 'blur' },
  ],
  applicantName: [
    { required: true, message: '请输入申请人姓名', trigger: 'blur' },
  ],
  phoneNumber: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    {
      // 自定义验证函数，见上说明
      validator: (rule, value, callback) => {
        return uni.$u.test.mobile(value);
      },
      message: '手机号码不正确',
      // 触发器可以同时用blur和change
      trigger: ['change','blur'],
    }
  ],
  verificationCode: [
    { required: true, message: '请输入验证码', trigger: 'blur' },
  ],
});

const handleSearch = (keyword) => {
  searchName.value = keyword
  searchFlag.value = keyword ? true : false
  console.log(keyword)
}
watch(() => searchName.value, (newValue) => {
  if (newValue) {
    // 模拟搜索门店
    // 这里可以替换为实际的搜索逻辑
     qryIndexList({
      pageNum:1,
      pageSize:30,
      storeName: newValue
  }).then(res=>{
        shopList.value =res
        searchOpen.value = true; // 显示搜索结果
  })
  } else {
    // 清空搜索结果
    shopList.value = [];
    searchOpen.value = false
  }
});
const handleConfirmItem = (item) => {
  form.value.storeId = item.storeId;
  form.value.shopName = item.storeFullName;
  searchName.value = item.storeFullName;
  searchFlag.value = false; // 清除搜索状态
  storeDetailsId(item.id).then(res=>{
    // bannerList.value = res.data.bannerList
    ShopStore.setShopInfo({
      ...res,
    })
    ohterStore.value = res
  })
  setTimeout(()=>{
       searchOpen.value = false
  },1000)

};
// 表单引用
const countdown = ref(0);
const isCounting = ref(false);

const getCode =async () => {
  if (isCounting.value) return;
  if (!form.value.phoneNumber) {
    uni.$u.toast('请输入手机号');
    return;
  }
  if (!uni.$u.test.mobile(form.value.phoneNumber)) {
    uni.$u.toast('手机号码格式不正确')
    return;
  }
  // 这里添加发送验证码的接口调用
  await smsCode({
    phone: form.value.phoneNumber,

  });

  countdown.value = 60; // 60秒倒计时
  isCounting.value = true;
  const timer = setInterval(() => {
    countdown.value--;
    if (countdown.value <= 0) {
      clearInterval(timer);
      isCounting.value = false;
    }
  }, 1000);
};
const  uFormRef= ref(null)
const submit =() =>{
  uFormRef.value.validate().then(valid => {
    if (valid) {
      // 需要校验的字段数组
      const requiredFields =  form.value.groupCardType==='A'?[
        { idCardFront: "身份证正面不能为空！" },
        { idCardBack: "身份证背面不能为空！" },
        { businessLicense: "营业执照不能为空！" },
      ]: [
        { idCardFront: "身份证正面不能为空！" },
        { idCardBack: "身份证背面不能为空！" },
      ];
      if(validateRequiredFields(form.value, requiredFields)){
        groupAdd({
          ...form.value,
          authorizedAmount: form.value.groupCardType==='A' ? shopInfo.businessAuthorizedAmount: shopInfo.familyAuthorizedAmount

        }).then(res=>{
          uni.$u.toast('提交成功')
          setTimeout(()=>{
            uni.navigateBack({
              delta:2
            })
          },1000)

        })
      }

      // uni.$u.toast('校验通过')
    } else {
      // uni.$u.toast('校验失败')
    }
  }).catch(() => {
    // 处理验证错误
    uni.$u.toast('校验失败')
  });
}
function validateRequiredFields(obj, requiredFields) {
  for (const fieldInfo of requiredFields) {
    const field = Object.keys(fieldInfo)[0]; // 获取字段名
    const message = fieldInfo[field]; // 获取提示信息

    if (!obj[field]) {
      uni.$u.toast(message)
      // console.error(message); // 提示字段不能为空
      return false; // 如果发现空值，立即返回 false
    }
  }

  return true; // 所有字段都不为空，返回 true
}

const end = () => {
  uni.$u.toast('倒计时结束');
};

const start = () => {
  uni.$u.toast('倒计时开始');
};
onLoad((e)=>{
  if(e.storeId){
    form.value.storeId = e.storeId
    storeId.value = e.storeId
  }
  if(e.groupCardType){
    form.value.groupCardType = e.groupCardType
  }
})
</script>

<style lang="scss" scoped>
@import "../style/common.scss";
page {

}
.open_team{
  box-sizing: border-box;
  width: 100%;
  padding: 0 52rpx;
  min-height: 100vh;
  padding-bottom: 200rpx;
  background-color: #ffffff;
  .search-area {
    position: relative;
    .search-shop-pot {
      display: none;
      width: calc(100% - 64rpx);
      min-height: 283rpx;
      max-height: 500rpx;
      position: absolute;
      top: 80rpx;
      left: 32rpx;
      background-color: #fff;
      border-radius: 10rpx;
      padding: 4rpx 24rpx;
      box-shadow: 0 6rpx 6rpx 1rpx rgba(171, 171, 171, 0.16);
      z-index: 5;
      &.active {
        display: block;
      }
      .search-item-pot{
        min-height: 275rpx;
        max-height: 402rpx;
      }
      .shop-item{
        padding: 20rpx 0;
        .title{
          font-size: 32rpx;
          font-weight: bold;
          color: #000;
        }
        .add{
          font-size: 24rpx;
          font-weight: normal;
          color: #636363;
          .small-img {
            width: 32rpx;
            height: 32rpx;
            margin-right: 12rpx;
          }
        }
        .cont{
          font-weight: bold;
          margin-top: 12rpx;
        }
        .btn{
          margin-top: 12rpx;
          width: 120rpx;
          height: 40rpx;
          line-height: 40rpx;
          text-align: center;
          background-color: #0080FF;
          border-radius: 8rpx;
          color: #fff;
          font-size: 24rpx;
          font-weight: normal;
        }
      }
    }
  }
  .round_wrap{
    box-sizing: border-box;
    width: 100%;
    height: 68rpx;
    background-color: #f2f2f2;
    border-radius: 200rpx;
    padding: 0 32rpx;
  }
  .tips{
    margin-top: 24rpx;
    font-size: 24rpx;
    color: red;
  }
}
.uploader {
  height: 339rpx;
  border: 1rpx dashed #999;
  border-radius: 16rpx;
  &.previous {
    margin-bottom: 24rpx;
  }
  .adrift {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    text-align: center;
    .icon {
      width: 52rpx;
      height: 44rpx;
    }
    .pic {
      width: 108rpx;
      height: 74rpx;
    }
    .describe {
      font-size: 24rpx;
      color: #999;
      margin-top: 12rpx;
      white-space: nowrap;
    }
  }
}
.disabled {
  //background: #e0e0e0;
  color: #aaa;
  pointer-events: none;
  border-radius: 8rpx;
}
</style>
